package com.mm.common.pipeline;



import com.mm.common.utils.ContextUtil;
import org.springframework.context.ApplicationContext;

/**
 * 流水线节点抽象类
 */
public abstract class PipelineNode {

    //Spring容器，用于从容器中获取处理者的bean
    protected static ApplicationContext applicationContext = ContextUtil.getContext();
    //产品
    protected Product product;
    //异常产品处理者，出现异常产品后的处理方式
    protected PipelineHandler exceptionHandler;


    /** ---------------------------------------------------------------------------------------------------------------------
     * @Method  : 设置Bean容器
     * @Describe: TODO
     **/
     public static void setApplicationContext(ApplicationContext applicationContext) {
        PipelineNode.applicationContext = applicationContext;
    }

    /** ---------------------------------------------------------------------------------------------------------------------
     * @Method  : 添加处理者,spring框架自动注入
     * @Describe: TODO
     **/
    public abstract <T extends PipelineHandler> PipelineNode addHandler(Class<T> bean);

    /** ---------------------------------------------------------------------------------------------------------------------
     * @Method  : 添加处理者,自行创建处理者对象
     * @Describe: TODO
     **/
    // 添加处理者
    public abstract PipelineNode addHandler(PipelineHandler handler);


    /** ---------------------------------------------------------------------------------------------------------------------
     * @Method  : 添加一个异常产品的处理者
     * @Describe: TODO
     **/
    public PipelineNode setExceptionHandler(PipelineHandler exceptionHandler) {
        this.exceptionHandler = exceptionHandler;
        return this;
    }



    /** ---------------------------------------------------------------------------------------------------------------------
     * @Method  : 结束流水线,返回数据
     * @Describe: TODO
     **/
     public  <T> T finish(Class<T> retType){
         //调用异常产品处理者处理异常产品
         if(product.getProductCode() == ProductCode.ABNORMAL){
             if(exceptionHandler != null){
                 Product product1 = exceptionHandler.process(product);
                 return product1.getData(retType);
             }else {
                 new PipelineException("未配置异常产品处理者").printStackTrace();
                 return null;
             }
         }
        return product.getData(retType);
    };



}
